package com.sukaiyi.generator.config.defaulttpl;

import cn.hutool.core.codec.Base64;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sukaiyi.generator.config.model.StructTemplate;
import com.sukaiyi.generator.config.model.TplType;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author sukaiyi
 * @date 2019/4/26
 */
public class DefaultTemplate {

    public static List<StructTemplate> load() {
        List<StructTemplate> templates = new ArrayList<>();

        List<InputStream> ises = getTemplateInputStreams();
        Gson gson = new GsonBuilder().create();
        for (InputStream is : ises) {
            String content = getContentAndClose(is);
            StructTemplate template = gson.fromJson(content, StructTemplate.class);
            templates.add(template);
        }
        Queue<StructTemplate> queue = new LinkedList<>(templates);
        while (!queue.isEmpty()) {
            StructTemplate tpl = queue.poll();
            if (tpl.getType() == TplType.MODULE) {
                List<StructTemplate> children = tpl.getChildren();
                if (children != null && children.size() > 0) {
                    queue.addAll(children);
                }
            } else {
                tpl.setContent(Base64.decodeStr(tpl.getContent()));
            }
        }
        return templates;
    }

    private static List<InputStream> getTemplateInputStreams() {
        List<String> paths = Arrays.asList(
                "/template/mybatis.json",
                "/template/csa-template.json"
        );
        List<InputStream> ises = new ArrayList<>(paths.size());
        for (String path : paths) {
            InputStream is = DefaultTemplate.class.getResourceAsStream(path);
            ises.add(is);
        }
        return ises;
    }

    private static String getContentAndClose(InputStream is) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
